var express = require('express');
var multiparty = require('multiparty');
var util = require('util');
var fs = require('fs');
var router = express.Router();

const filesPath = "/Users/liuxing/Workspaces/oschina/liuxing/NodejsExample/files/";

/**
 * 文件列表
 */
router.get('/', function (req, res, next) {
    fs.readdir(filesPath, function (err, files) {
        if (err) {
            console.log(err);
            return;
        }

        res.send(files);
    });
});

/**
 * 下载文件
 */
router.get('/:filename', function (req, res, next) {
    var filename = req.params.filename;
    res.download(filesPath + filename, filename, function (error) {

    });
});

/**
 * 上传文件
 *
 */
router.post('/upload', function (req, res, next) {

    //生成multiparty对象，并配置上传目标路径
    var form = new multiparty.Form({uploadDir: './files/'});

    //上传完成后处理
    form.parse(req, function (err, fields, files) {
        var filesTmp = JSON.stringify(files, null, 2);

        if (err) {
            console.log('parse error: ' + err);
        } else {
            console.log('parse files: ' + filesTmp);

            for (let file in files) {
                files[file].forEach(function (inputFile) {
                    var uploadedPath = inputFile.path;
                    var dstPath = './files/' + inputFile.originalFilename;

                    //重命名为真实文件名
                    fs.rename(uploadedPath, dstPath, function (err) {
                        if (err) {
                            console.log('rename error: ' + err);
                        } else {
                            console.log('rename ok');
                        }
                    });
                });
            }
        }

        res.send({fields: fields, files: files});
    });
});

module.exports = router;
